package com.gaga.common.utils;

import lombok.Getter;

import javax.sound.sampled.*;
import java.io.File;

/**
 * @author liujia
 * @version 1.0
 * @date 2025/3/30-15:32
 */
public class AudioPlayerUtils implements LineListener {

    @Getter
    private Clip clip;

    /**
     * 记录暂停位置
     */
    @Getter
    private long pausePosition = 0;

    /**
     * 是否暂停
     */
    private volatile boolean isPaused = false;

    /**
     * 标记是否为用户主动暂停
     */
    private volatile boolean isUserPaused = false;

    /**
     * 播放完成回调方法
     */
    private Runnable onPlaybackFinished;

    // 添加完成回调方法
    public void setOnPlaybackFinished(Runnable callback) {
        this.onPlaybackFinished = callback;
    }

    /**
     * 初始化音频并绑定设备
     */
    public void init(String filePath, String deviceName) {
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                return;
            }
            AudioInputStream originalStream = AudioSystem.getAudioInputStream(file);
            Mixer.Info targetMixerInfo = DeviceInfoUtils.getTargetAudioDevice(deviceName, true);
            if (targetMixerInfo == null) {
                throw new IllegalArgumentException("设备未找到: " + deviceName);
            }

//            AudioFormat originalFormat = originalStream.getFormat();
//            // 根据速度调整采样率
//            AudioFormat targetFormat = new AudioFormat(
//                    originalFormat.getEncoding(),
//                    originalFormat.getSampleRate(), // 修改采样率
//                    originalFormat.getSampleSizeInBits(),
//                    originalFormat.getChannels(),
//                    originalFormat.getFrameSize(),
//                    originalFormat.getFrameRate(), // 修改帧率
//                    originalFormat.isBigEndian()
//            );
//
//            // 检查是否支持格式转换
//            if (!AudioSystem.isConversionSupported(targetFormat, originalFormat)) {
//                throw new IllegalArgumentException("不支持的速度格式转换");
//            }
//
//            // 转换为调整后的音频流
//            AudioInputStream audioStream = AudioSystem.getAudioInputStream(targetFormat, originalStream);
//
//            Mixer mixer = AudioSystem.getMixer(targetMixerInfo);
//            clip = (Clip) mixer.getLine(new DataLine.Info(Clip.class, audioStream.getFormat()));
//            clip.open(audioStream);
//            System.out.println("原始格式: " + originalFormat);
//            System.out.println("目标格式: " + targetFormat);
//            System.out.println("实际播放格式: " + clip.getFormat());

            Mixer mixer = AudioSystem.getMixer(targetMixerInfo);
            clip = (Clip) mixer.getLine(new DataLine.Info(Clip.class, originalStream.getFormat()));
            clip.open(originalStream);
            // 添加监听器
            clip.addLineListener(this);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 播放恢复
     */
    public void play() {
        if (clip != null && !clip.isRunning()) {
            if (isPaused) {
                clip.setMicrosecondPosition(pausePosition);
                isPaused = false;
                isUserPaused = false;
            }
            clip.start();
        }
    }

    /**
     * 暂停
     */
    public void pause() {
        if (clip != null && clip.isRunning()) {
            isUserPaused = true;
            pausePosition = clip.getMicrosecondPosition();
            clip.stop();
            isPaused = true;
        }
    }

    /**
     * 停止并重置
     */
    public void stop() {
        if (clip != null) {
            clip.stop();
            clip.close();
            pausePosition = 0;
            isPaused = false;
            isUserPaused = false;
            if (onPlaybackFinished != null) {
                onPlaybackFinished.run(); // 触发回调
            }
        }
    }


    /**
     * 设置音量
     *
     * @param volume 音量值，范围从 0.0 到 1.0
     */
    public void setVolume(float volume) {
        if (clip != null && clip.isOpen()) {
            FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
            float min = gainControl.getMinimum();
            float max = gainControl.getMaximum();
            float value = min + (max - min) * volume;
            gainControl.setValue(value);
        }
    }

    /**
     * 修改事件监听逻辑
     *
     * @param event a line event that describes the change
     */
    @Override
    public void update(LineEvent event) {
        if (event.getType() == LineEvent.Type.STOP) {
            // 仅在非用户主动暂停时触发停止
            if (!isUserPaused) {
                System.out.println("播放自然结束");
                stop();
            }
        }
    }


    public static void main(String[] args) throws Exception {
        AudioPlayerUtils player = new AudioPlayerUtils();
        player.init("C:/Users/lenovo/Desktop/test/6.wav", "耳机 (AirPro Stereo)");
        // 播放
        player.play();
        // 模拟暂停/恢复操作
        player.pause();
        System.out.println("已暂停");

        player.play();
        System.out.println("已恢复");


        // 等待播放完成（实际应用中可用事件监听或GUI按钮控制）
        while (player.clip.isRunning()) {
            Thread.sleep(100);
        }

        // 输入的 WAV 文件路径
        String inputFilePath = "C:/Users/lenovo/Desktop/test/1.mp3";
        // 速度因子，例如 0.5 表示减慢到原来的一半，2.0 表示加快到原来的两倍
        double speedFactor = 1.5;


    }
}
